<template>
  <div class="user-container">
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="sizeInfo.query"
            clearable
            @change="getUserList()"
            placeholder="请输入用户名"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUser = !addUser"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="userList" stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column
          label="用户名"
          prop="username"
          align="center"
        ></el-table-column>
        <el-table-column
          label="角色"
          prop="role_name"
          align="center"
        ></el-table-column>
        <el-table-column
          label="手机号"
          prop="mobile"
          align="center"
        ></el-table-column>
        <el-table-column
          label="角色"
          prop="role_name"
          align="center"
        ></el-table-column>
        <el-table-column
          label="邮箱"
          prop="email"
          align="center"
        ></el-table-column>
        <el-table-column
          label="创建时间"
          prop="create_time"
          align="center"
        ></el-table-column>
        <el-table-column label="状态" prop="mg_state" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="onUserStateChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="editUser(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="editUser(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :page="sizeInfo.pagenum"
        :pageSize="sizeInfo.pagesize"
        :total="total"
        @page-change="onPageChange"
        @size-change="onSizeChange"
      ></pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUser"
      width="50%"
      @close="resetForm"
    >
      <el-form
        ref="addFormRef"
        label-width="80px"
        :model="addForm"
        :rules="addFormRules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile" maxlength="11"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUser = false">取 消</el-button>
        <el-button type="primary" @click="onConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editUserDialog"
      width="50%"
      @close="resetEditForm"
    >
      <el-form
        ref="editFormRef"
        label-width="80px"
        :model="editForm"
        :rules="editFormRules"
      >
        <el-form-item label="用户名">
          <el-input disabled v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile" maxlength="11"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialog = false">取 消</el-button>
        <el-button type="primary" @click="onEditConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  userList,
  userStateChange,
  addUser,
  findUser,
  saveByEdit,
  deleteUserById,
} from '../../api/user'
import pagination from '@/component/pagination/pagination.vue'
export default {
  components: { pagination },
  name: 'User',
  data() {
    // 验证邮箱的规则
    const checkEmail = (rule, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入正确的邮箱地址'))
    }
    // 验证手机号的规则
    const checkMobile = (rule, value, cb) => {
      const regMobile = /^1[3|4|5|7|8|9][0-9]{9}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入正确的手机号'))
    }
    return {
      userList: [], // 用户列表
      total: 0, // 总条数
      sizeInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10,
      },
      editUserDialog: false, // 修改用户对话框
      editForm: {}, // 根据id查询到的用户信息
      addUser: false, // 控制显示隐藏添加用户对话框
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      }, // 表单绑定的数据
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名长度在3到10个字符之间',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '用户名长度在6到15个字符之间',
            trigger: 'blur',
          },
        ],
        email: [{ validator: checkEmail, required: true, trigger: 'blur' }],
        mobile: [{ validator: checkMobile, required: true, trigger: 'blur' }],
      }, // 添加表单的验证
      editFormRules: {
        email: [{ validator: checkEmail, required: true, trigger: 'blur' }],
        mobile: [{ validator: checkMobile, required: true, trigger: 'blur' }],
      }, // 修改表单的验证
    }
  },
  mounted() {
    this.getUserList()
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      try {
        const res = await userList(this.sizeInfo)
        if (res.meta.status === 200) {
          this.userList = res.data.users
          this.total = res.data.total
        } else {
          this.$message.error(res.meta.msg)
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 修改用户状态
    async changeState(value) {
      try {
        const res = await userStateChange(value.id, value.mg_state)
        if (res.meta.status === 200) {
          this.$message.success(res.meta.msg)
        } else {
          value.mg_state = !value.mg_state
          this.$$message.error(res.meta.msg)
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 每页条数改变
    onSizeChange(val) {
      this.sizeInfo.pagesize = val
      this.getUserList()
    },
    // 页码改变
    onPageChange(val) {
      this.sizeInfo.pagenum = val
      this.getUserList()
    },
    // 用户状态改变
    onUserStateChange(value) {
      this.changeState(value)
    },
    // 重置表单
    resetForm() {
      this.$refs.addFormRef.resetFields()
    },
    resetEditForm() {
      this.$refs.editFormRef.resetFields()
    },
    // 添加用户表单确认按钮
    onConfirm() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        try {
          const res = await addUser(this.addForm)
          if (res.meta.status === 201) {
            this.$message.success(res.meta.msg)
            this.addUser = false
            this.getUserList()
          } else {
            this.$message.error(res.meta.msg)
          }
        } catch (error) {}
      })
    },
    // 编辑用户
    async editUser(val) {
      try {
        this.editUserDialog = true
        const res = await findUser(val)
        if (res.meta.status === 200) {
          this.editForm = res.data
        } else {
          this.$message.error(res.meta.msg)
        }
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑用户确认按钮
    onEditConfirm() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        try {
          const res = await saveByEdit(this.editForm)
          if (res.meta.status === 200) {
            this.$message.success(res.meta.msg)
            this.editUserDialog = false
            this.getUserList()
          } else {
            this.$message.error(res.meta.msg)
          }
        } catch (error) {}
      })
    },
    deleteUser(id) {
      this.$confirm('是否删除用户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deleteUserById(id)
            .then((res) => {
              console.log(res)
              if (res.meta.status === 200) {
                this.getUserList()
                this.$message({
                  type: 'success',
                  message: '删除成功!',
                })
              } else {
                this.$message({
                  type: 'error',
                  message: err.meta.msg,
                })
              }
            })
            .catch((err) => {
              console.log(err)
              this.$message({
                type: 'error',
                message: err.meta.msg,
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
  },
}
</script>

<style lang="less" scope>
.user-container {
  .box-card {
    .el-table {
      margin-top: 15px;
    }
  }
}
</style>
